<?php

namespace App\Listeners;

use App\Events\Event;
use App\Events\TeacherEvent;


class TeacherListener extends Listener
{

    /**
     * @param TeacherEvent $event
     */
    public function handle(TeacherEvent $event)
    {
        switch($event->action)
        {
            case Event::CREATE:
                $this->create($event); break;
            case Event::UPDATE:
                $this->update($event); break;
            case Event::DELETE:
                $this->delete($event); break;
            default: break;
        }
    }


    /**
     * 注册并添加老师到机构
     * @param TeacherEvent $event
     * @throws \Exception
     */
    protected function create(TeacherEvent $event)
    {
        try{
            $this->register($event->teacherAccount,$event->teacherName,$event->password);
            $this->setUri('addTeacher');
            $cfile = $this->uploadCheck($event->Filedata);
            $data = $this->dataMaker();
            $data["teacherAccount"] = $event->teacherAccount;
            $data["teacherName"] = $event->teacherName;
            $data["Filedata"] = $cfile;
            $this->setRequest($data);
            $result = $this->callEeoApi();

            $code = $result['error_info']['errno'] ;
            if(in_array($code,[1,133])) {
                $event->setStid($result['data']);
            }else{
                throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
            }
        }catch (\Exception $e){
            throw $e;
        }

    }


    /**
     * 修改教师信息
     * @param TeacherEvent $event
     * @throws \Exception
     */
    protected function update(TeacherEvent $event)
    {
        try{
            $this->editUser($event->teacherAccount,$event->teacherName);
            $this->setUri('editTeacher');
            $cfile = $this->uploadCheck($event->Filedata);
            $data = $this->dataMaker();
            $data["st_id"] = $event->stid;
            $data["teacherName"] = $event->teacherName;
            $data["Filedata"] = $cfile;
            $this->setRequest($data);
            $result = $this->callEeoApi();
            if($result['error_info']['errno'] <> 1) {
                throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
            }
        }catch (\Exception $e){
            throw $e;
        }
    }


    /**
     * 删除
     * @param $event
     */
    protected function delete(TeacherEvent $event)
    {

    }



}
